<template>
  <div class="chat">
    <Panel>
      <div class="caseMessage">
        <div class="leftNum">到场</div>
        <div class="caseMessage-bottom">
          <div class="rightBox">
            <div>案件计时</div>
            <div id="timeBox">{{ stratTime }}</div>
          </div>
          <div class="caseMessage-bottom" style="height: 60px; overflow-y: auto">
            {{ alarmTitle }}
          </div>
        </div>
      </div>
    </Panel>
    <Panel class="mt-[15px]">
      <div class="chatBox">
        <div class="itemBox">
          <div
            v-for="(item, index) in chatList"
            :key="index"
            class="chatMessageBox"
            :class="{ myChatMessage: item.isMe == true }"
          >
            <h2>{{ timeTitle }}</h2>
            <!-- 系统信息 -->
            <div v-if="item.msgType == 'sys_notice'" class="systemMessage">
              <img src="@/assets/image/icon_error.png" alt="" />
              <span>{{ item.message }}</span>
            </div>
            <!-- 用户所发信息 -->
            <!-- <div v-else> -->
            <div>
              <div class="titleBox">
                <img :src="item.avatar" alt="" />
                <span>{{ item.userName }}</span>
              </div>
              <!-- 详细信息 -->
              <div class="chatDetail" style="padding-bottom: 5px">
                <div v-if="item.msgType == 'text'">{{ item.content || '消息内容' }}</div>
                <!-- 图片信息 -->
                <div v-if="item.msgType == 'image'" class="imgBox">
                  <img :src="item.content" style="margin: 5px; object-fit: contain" alt="" />
                </div>
                <div v-if="item.msgType == 'video'" class="imgBox">
                  <video
                    :src="item.content"
                    width="100%"
                    height="100%"
                    controls
                    style="margin: 5px"
                  ></video>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Panel>
  </div>
</template>
<script setup lang="ts">
import {
  groupListByAjxxidAndLx,
  queryUserSig,
  queryGroupMembers,
  queryFinishGroupMessageList,
  queryUnfinishedGroupMessage,
  queryGroupList,
} from '@/service'
import Touxiang from '@/assets/image/chat_person.png'
import Zhzx from '@/assets/image/zhihui.png'
import Prompt from '@/assets/image/icon_error.png'
import TIM from 'tim-js-sdk'
import axios from 'axios'
import { useBusinessStore } from '@/store'
import { on } from 'events'
const store = useBusinessStore()

// 警情详细描述
const alarmTitle = computed(() => {
  return store.jqInfo.ajms
})

watch(alarmTitle, (newVal, oldVal) => {}, { immediate: true })
// 案件计时
const stratTime = computed(() => {
  return store.jqInfo.lasj
})
// 计算时间计时的方法
function timingTime() {
  const start = stratTime.value
  const startTime = new Date(start).getTime()
  const currentTime = new Date().getTime()
  // timeInter.value = setInterval(() => {
  //   (document.getElementById('timeBox') as HTMLElement).innerHTML = timingTime()
  // }, 60000);
  const difference = currentTime - startTime
  const m = Math.floor(difference / 1000)
  const mm = m % 60 // 秒
  const f = Math.floor(m / 60)
  const ff = f % 60 // 分钟
  const s = Math.floor(f / 60) // 小时
  const ss = s % 24
  const day = Math.floor(s / 24) // 天数

  const checkTime = function (i: any) {
    if (i < 10) {
      i = '0' + i
    }
    return i
  }
  return checkTime(ss) + ':' + checkTime(ff) + ':' + checkTime(mm)
}
const timeInter: any = ref()
timeInter.value = setInterval(() => {
  ;(document.getElementById('timeBox') as HTMLElement).innerHTML = timingTime()
}, 1000)

onMounted(() => {
  ;(document.getElementById('timeBox') as HTMLElement).innerHTML = timingTime()
})
// 销毁计时器
onUnmounted(() => {
  clearInterval(timeInter.value)
  timeInter.value = null
})

// 文书

const chatList: any = ref([
  // {
  //   isMe: false,
  //   userName: '石门坎站',
  //   avatar: Touxiang,
  //   msgType: 'text',
  //   content: '测试消息内容'
  // },
  // {
  //   isMe: true,
  //   userName: '指挥中心',
  //   avatar: Zhzx,
  //   msgType: 'text',
  //   content: '消息内容'
  // },
  // {
  //   isMe: false,
  //   userName: '石门坎站',
  //   avatar: Zhzx,
  //   msgType: 'image',
  //   content: ''
  // },
])

let tim: any = null
// 用户id
const openid: any = ref('admin') // 13851694795 15862707666
// 当前用户信息 姓名暂定“指挥中心”
const lqryInfo: any = ref({
  lxrXm: '指挥中心',
})
// const groupId = ref("@TGS#2L5DM6PIA");
const groupId = ref('')
let whetherJoinGroupFlag: any = ref()

const imLogin = async () => {
  tim = TIM.create({ SDKAppID: 1400672021 })
  bindIMEvent(tim)
  let userSig: string = localStorage.getItem('userSig') || ''
  if (!userSig) {
    await queryUserSig({ userid: openid.value, expire: 7 * 24 * 3600 })
      .then((res: any) => {
        if (res.result.resultCode === '000000') {
          // 报错 用于 userSig
          userSig = res.data
          localStorage.setItem('userSig', userSig)
        }
      })
      .catch((e: any) => {
        console.log('获取 userSig 出错', e)
      })
  }
  const params = {
    userID: openid.value || '',
    userSig: userSig || '',
  }

  tim
    .login(params)
    .then((imResponse: any) => {
      // 获取消息列表
      if (imResponse.data.actionStatus === 'OK') {
        console.log('IM 登陆成功')
      }
    })
    .catch((imError: any) => {
      console.log('IM 登陆失败', imError)
    })
}
/**
 * 绑定 IM　事件
 * @param tim
 */
function bindIMEvent(tim: any) {
  // 监听事件，例如：
  tim.on(TIM.EVENT.SDK_READY, function (event: any) {
    // 收到离线消息和会话列表同步完毕通知，接入侧可以调用 sendMessage 等需要鉴权的接口
    // event.name - TIM.EVENT.SDK_READY
    // console.log('获取历史消息', event);
    // 获取历史消息列表
    getMessageList(groupId.value)
  })
  tim.on(TIM.EVENT.MESSAGE_RECEIVED, function (event: any) {
    // 系统推送的通知消息
    // 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
    // event.name - TIM.EVENT.MESSAGE_RECEIVED
    // event.data - 存储 Message 对象的数组 - [Message]
    // console.log('系统推送的通知消息', event)
    handleReceiveGroupMessage(event)
  })
  tim.on(TIM.EVENT.MESSAGE_REVOKED, function (event: any) {
    // 收到消息被撤回的通知
    // event.name - TIM.EVENT.MESSAGE_REVOKED
    // event.data - 存储 Message 对象的数组 - [Message] - 每个 Message 对象的 isRevoked 属性值为 true
  })
  tim.on(TIM.EVENT.MESSAGE_READ_BY_PEER, function (event: any) {
    // SDK 收到对端已读消息的通知，即已读回执。使用前需要将 SDK 版本升级至 v2.7.0 或以上。仅支持单聊会话。
    // event.name - TIM.EVENT.MESSAGE_READ_BY_PEER
    // event.data - event.data - 存储 Message 对象的数组 - [Message] - 每个 Message 对象的 isPeerRead 属性值为 true
  })
  tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, function (event: any) {
    // 收到会话列表更新通知，可通过遍历 event.data 获取会话列表数据并渲染到页面
    // event.name - TIM.EVENT.CONVERSATION_LIST_UPDATED
    // event.data - 存储 Conversation 对象的数组 - [Conversation]
  })
  tim.on(TIM.EVENT.GROUP_LIST_UPDATED, function (event: any) {
    // 收到群组列表更新通知，可通过遍历 event.data 获取群组列表数据并渲染到页面
    // event.name - TIM.EVENT.GROUP_LIST_UPDATED
    // event.data - 存储 Group 对象的数组 - [Group]
    // 接收到群聊消息
    // console.log('接收到群聊消息', event);
  })
  tim.on(TIM.EVENT.PROFILE_UPDATED, function (event: any) {
    // 收到自己或好友的资料变更通知
    // event.name - TIM.EVENT.PROFILE_UPDATED
    // event.data - 存储 Profile 对象的数组 - [Profile]
  })
  tim.on(TIM.EVENT.BLACKLIST_UPDATED, function (event: any) {
    // 收到黑名单列表更新通知
    // event.name - TIM.EVENT.BLACKLIST_UPDATED
    // event.data - 存储 userID 的数组 - [userID]
  })
  tim.on(TIM.EVENT.ERROR, function (event: any) {
    // 收到 SDK 发生错误通知，可以获取错误码和错误信息
    // event.name - TIM.EVENT.ERROR
    // event.data.code - 错误码
    // event.data.message - 错误信息
  })
  tim.on(TIM.EVENT.SDK_NOT_READY, function (event: any) {
    // 收到 SDK 进入 not ready 状态通知，此时 SDK 无法正常工作
    // event.name - TIM.EVENT.SDK_NOT_READY
  })
  tim.on(TIM.EVENT.KICKED_OUT, function (event: any) {
    // 收到被踢下线通知
    // event.name - TIM.EVENT.KICKED_OUT
    // event.data.type - 被踢下线的原因，例如:
    //    - TIM.TYPES.KICKED_OUT_MULT_ACCOUNT 多实例登录被踢
    //    - TIM.TYPES.KICKED_OUT_MULT_DEVICE 多终端登录被踢
    //    - TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED 签名过期被踢 （v2.4.0起支持）。
  })
}

// 获取群组id
const getWsList = () => {
  groupListByAjxxidAndLx({ ajxxid: jqId.value, qzlx: '01' }).then((res: any) => {
    if (res.length > 0) {
      groupId.value = res[0].qzid
      whetherJoinGroupFlag = getGroupMemberList(groupId.value, openid.value)
      getMessageList(groupId.value)
      if (res[0].sfQljs == 0) {
        getUnfinishedMessage(groupId.value)
      } else if (res[0].sfQljs == 1) {
        // 如果群聊结束
        queryFinishGroupMessageList(res[0].qzid)
      }
    } else {
      // console.log('该警情暂无群组id');
    }
  })
}

/** 获取当前会话list */
const currentMessageList = ref<any>([]) // 当前拉取的消息列表
const nextReqMessageID = ref<string>('') // 用于续拉，分页续拉时需传入该字段。
const isCompleted = ref<boolean>(false) // 表示是否已经拉完所有消息。isCompleted 为 true 时，nextReqMessageID 为
/** 第一次拉群群聊会话列表 */
function getMessageList(groupId: any) {
  tim
    .getMessageList({ conversationID: `GROUP${groupId}`, count: 15 })
    .then((messageResponse: any) => {
      // console.log("第一次拉取群聊会话", messageResponse);
      handleHistoryMessage(messageResponse.data.messageList, false)
      currentMessageList.value = messageResponse.data.messageList
      nextReqMessageID.value = messageResponse.data.nextReqMessageID
      isCompleted.value = messageResponse.data.isCompleted
    })
}

/*** 处理 IM　历史消息列表 */
function handleHistoryMessage(message: any, isLoad: boolean) {
  const historyMessageList: any = []
  message.forEach((item: any) => {
    const handleMessage: any = handleMessageType(item.payload?.text)
    if (!handleMessage) {
      return
    }
    if (JSON.stringify(handleMessage) == '{}') {
      return
    }
    const msg = {
      isMe: item.from === openid.value ? true : false,
      userName: item.from === openid.value ? lqryInfo.value.lxrXm : '石门坎站',
      avatar: handleMessage.avatar || Touxiang,
      // mobileNumber: item.from === openid.value ? lqryInfo.lxrLxdh : '',
      msgType: handleMessage?.type,
      content: handleMessage?.content,
    }
    historyMessageList.push(msg)
  })
  // console.log("处理完消息列表", historyMessageList);
  // 将处理后的消息 传入消息列表中，判断是否二次加载，二次加载则将消息push到 chatList 中
  // if (isLoad) {
  //   chatList.value.push(historyMessageList);
  // } else {
  //   chatList.value = historyMessageList;
  // }
}

/**
 * 接收到群聊消息
 * 首先判断 群聊消息的发送人，在将消息内容push到 chatList
 */
function handleReceiveGroupMessage(event: any) {
  // 处理在群聊时的消息发送
  handleSendSuccess(event, 'other')
}

/**
 * 处理发送成功的消息;
 * 包含 自己发送的消息及群聊其他用户发送的消息
 */
const timeTitle = ref('当前')
let timer: any
function handleSendSuccess(res: any, type: string) {
  // console.log("处理发送成功后的返回值", res);
  let item: any
  if (type === 'owner') {
    item = res.data.message
  } else {
    item = res.data[0]
  }
  const handleMessage = handleMessageType(item.payload?.text)
  if (!handleMessage) {
    return
  }
  if (JSON.stringify(handleMessage) == '{}') {
    return
  }
  const msg = {
    isMe: item.from === openid.value ? true : false,
    userName: item.from === openid.value ? lqryInfo.value.lxrXm : '石门坎站',
    avatar: handleMessage.userAvatar || Touxiang,

    // mobileNumber: item.from === openid.value ? lqryInfo.lxrLxdh : '',
    msgType: handleMessage?.type,
    content: handleMessage?.content,
  }
  chatList.value.push(msg)
  // 隔两分钟后计算一次时间
  timer = setInterval(() => {
    timeTitle.value = calculateDiffTime(item.time)
  }, 120000)
}
/**
 * 计算 当前时间与消息推送时间之差
 * @param start_time 推送时间
 */
function calculateDiffTime(start_time: any) {
  if (!parseInt(start_time)) {
    return '-'
  }
  const endTime: any = Math.round((new Date() as any) / 1000)
  const timeDiff = endTime - start_time
  let day = parseInt((timeDiff / 86400) as any)
  let hour = parseInt(((timeDiff % 86400) / 3600) as any)
  let minute = parseInt(((timeDiff % 3600) / 60) as any)

  day = (day ? day + '天' : '') as any
  hour = (hour ? hour + '小时' : '') as any
  minute = (minute ? minute + '分钟' : '') as any
  return day + hour + minute + '之前'
}

/**
 * 获取群成员列表, 判断成员列表中是否包含自己
 */
async function getGroupMemberList(groupID: string, openid: string) {
  const params = {
    groupIdList: groupID,
  }
  await queryGroupMembers(params)
    .then((res: any) => {
      console.log('查询群成员列表', res)
      if (res.result.resultCode == '000000') {
        let index
        index = res.data?.ryList.findIndex((item: any) => item.memberAccount === openid)
        return index
      }
    })
    .catch((e: any) => {
      console.log('查询群成员出错', e)
      return -1
    })
}

/** 警情状态未结束 调用接口获取数据 */
function getUnfinishedMessage(group: string) {
  const params = {
    groupId: group,
    reqMsgNumber: 15,
    reqMsgSeq: 3,
    userid: 'admin',
  }
  axios
    .post(window.ApiDev.server3, params)
    .then((res: any) => {
      console.log('未结束警情历史消息', res)
      if (res.data.result.resultCode === '000000') {
        handleServiceMessage(res.data.data)
      }
    })
    .catch((e: any) => {
      // console.log("获取未结束警情历史消息出错", e);
    })
}

/** 处理 服务端查询到的消息列表  包含 已经结束的警情 和当前正在处理的警情 */
function handleServiceMessage(res: any) {
  const historyMessageList: any = []
  res.rspMsgList.length &&
    res.rspMsgList.forEach((item: any) => {
      console.log('消息 list', item.msgBody[0])
      const handleMessage: any = handleMessageType(item.msgBody[0].msgContent?.Text)
      console.log(handleMessage)
      if (!handleMessage) {
        return
      }
      if (JSON.stringify(handleMessage) == '{}') {
        return
      }
      const msg = {
        isMe: item.from === openid.value ? true : false,
        userName: item.from === openid.value ? lqryInfo.value.lxrXm : '石门坎站',
        avatar: handleMessage.avatar || Touxiang,
        // mobileNumber: item.from === openid.value ? lqryInfo.lxrLxdh : '',
        msgType: handleMessage?.type,
        content: handleMessage?.content,
      }
      historyMessageList.push(msg)
    })
  chatList.value = historyMessageList
}

/**
 * 处理接收到的消息内容，根据im传递的payload.text内容判断出发送消息的类型： text、image、video
 * @param text
 */
function handleMessageType(text: string) {
  if (text == undefined) {
    return {}
  }
  return JSON.parse(text)
}

onMounted(() => {
  imLogin()
  if (whetherJoinGroupFlag !== -1) {
    imLogin()
  } else {
    // 不在群聊中, 则也要
    getUnfinishedMessage(groupId.value)
  }
  // // 监听鼠标事件到底部
  // let scrollDiv = document.getElementById("itemBox") as HTMLElement;
  // scrollDiv.scrollTop = scrollDiv.scrollHeight;
})
onUnmounted(() => {
  getWsList()
  // console.log("判断是否在群聊中", whetherJoinGroupFlag);
  clearInterval(timer)
  // 警情未结束则页面销毁则退出登陆
  // if (alertState.value !== 1) {
  tim
    .logout()
    .then((imResponse: any) => {})
    .catch((imError: any) => {})
  // }
})

// 监听警情ID
const jqId = computed(() => {
  return store.jqInfo.id
})
watch(
  jqId,
  (newVal, oldVal) => {
    // getWsList(newVal);
  },
  { immediate: true }
)

// 轮询文书消息
const timer2 = setInterval(() => {
  console.log('文书信息已拉取')
  getWsList()
}, 5000)
onUnmounted(() => {
  clearInterval(timer2)
})
</script>
<style lang="less" scoped>
.caseMessage {
  height: 200px;
  color: #fff;
  padding: 10px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  // background: rgba(1, 10, 15, 0.5);

  .leftNum {
    width: 110px;
    height: 120px;
    font-size: 30px;
    color: aqua;
    font-weight: bolder;
    background: url(@/assets/image/daochang.png) no-repeat;
    text-align: center;
    line-height: 120px;
  }

  .rightBox {
    color: #ff3333;
    padding-left: 10px;
    font-weight: bolder;

    div:nth-of-type(1) {
      font-size: 20px;
    }

    div:nth-of-type(2) {
      font-size: 56px;
      line-height: 60px;
      font-family: Digitaldream;
    }
  }

  .caseMessage-bottom {
    width: 326px;
    margin-top: 5px;
    font-size: 20px;
    border-radius: 8px;
    font-weight: bold;
  }
}

.chat {
  width: 498px;
  position: absolute;
  left: 5px;
  top: 0;
  z-index: 9;
  height: 1030px !important;
  margin-top: 28px;

  .chatBox {
    height: 760px;
    color: #fff;
    padding: 10px;
    margin-top: 10px;
    overflow-y: auto !important;

    h2 {
      text-align: center;
      font-size: 16px;
    }

    .itemBox {
      overflow: hidden;
    }

    .chatMessageBox {
      width: 100%;
      float: left;

      .titleBox {
        height: 30px;
        line-height: 30px;
        font-size: 20px;
        font-weight: bolder;
        display: flex;

        img {
          width: 30px;
          height: 30px;
          border: none;
          margin: 0 5px;
        }
      }

      .chatDetail {
        padding: 10px;
        padding-bottom: 0;
        margin-bottom: 10px;
        background: rgba(0, 255, 255, 0.2);
        border-radius: 5px;
        font-size: 20px;
        margin-left: 40px;
        margin-right: 100px;

        .imgBox {
          display: flex;
          overflow-x: auto;
          flex-wrap: nowrap;

          img {
            cursor: pointer;
            width: 90px;
            height: 70px;
            // border: none;
          }
        }
      }
    }

    .myChatMessage {
      float: right;

      .titleBox {
        display: flex;
        flex-direction: row-reverse;
      }

      .chatDetail {
        background: rgba(0, 255, 204, 1);
        color: #333;
        font-size: 20px;
        font-weight: bolder;
        border-radius: 4px;
        margin-right: 40px;
        margin-left: 100px;
      }
    }

    .systemMessage {
      margin-left: 180px;
      margin-bottom: 10px;
      font-size: 16px;
      display: flex;
      align-items: center;

      img {
        width: 20px;
        height: 20px;
        border: none;
        margin-right: 5px;
      }
    }
  }
}
</style>
